let colors = config.colors
let teams = config.teams
let r = races.length
let n = colors.length
let m = teams.length
//  ,
//
//  t
//  u
//  i
//
//  q
//  i
//  a
//  n

let colorTotalScore = new Array(n)
for (let i = 0; i < n; ++i)
	colorTotalScore[i] = 0
let teamTotalScore = new Array(m)
for (let i = 0; i < m; ++i)
	teamTotalScore[i] = 0

for (let raceID = 0; raceID < r; ++raceID) {
	let race = races[raceID]
	let colorScore = race.score

	let teamScore = new Array(m)
	for (let i = 0; i < m; ++i)
		teamScore[i] = 0
	for (let i = 0; i < n; ++i) {
		let score = colorScore[i]
		let teamID = colors[i].team
		teamScore[teamID] += score
	}

	race.colorScore = colorScore
	race.teamScore = teamScore

	race.colorTotal = new Array(n)
	race.teamTotal = new Array(m)
	for (let i = 0; i < n; ++i)
		race.colorTotal[i] = (colorTotalScore[i] += colorScore[i])
	for (let i = 0; i < m; ++i)
		race.teamTotal[i] = (teamTotalScore[i] += teamScore[i])
}

function calcTeamTotalScore(key, items) {
	console.log(key)
	let k = items.length
	let lastRank
	let result = new Array(r)

	for (let raceID = 0; raceID < r; ++raceID) {
		let race = races[raceID]
		let raceName = race.name
		let totalScore = race[key]
		console.log(raceName)

		let list = new Array(k)
		for (let i = 0; i < k; ++i)
			list[i] = {
				id: i,
				score: totalScore[i]
			}
		list.sort(function (a, b) { return b.score - a.score })
		let rank = 0, last = undefined, thisRank = new Array(k), info = new Array(k)
		for (let i = 0; i < k; ++i) {
			let id = list[i].id
			let score = list[i].score
			if (score !== last) {
				last = score
				rank = i + 1
			}
			thisRank[id] = rank
			let delta
			if (lastRank)
				delta = lastRank[id] - rank
			info[i] = {
				id: id,
				score: score,
				rank: rank,
				delta: delta
			}
			console.log(id, items[id].name, score, rank, delta)
		}
		result[raceID] = info
		lastRank = thisRank
	}
	return result
}
let colorScore = calcTeamTotalScore('colorScore', colors)
let colorTotal = calcTeamTotalScore('colorTotal', colors)
let teamScore = calcTeamTotalScore('teamScore', teams)
let teamTotal = calcTeamTotalScore('teamTotal', teams)